package com.hisense.settings;

import android.app.ActivityManager;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.ContentResolver;
import android.content.Context;
import android.util.Log;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.preference.Preference;
import android.preference.PreferenceActivity;
import android.preference.PreferenceScreen;
import android.widget.Toast;
import android.content.pm.IPackageDataObserver;
import android.database.Cursor;

import com.android.settings.R;
public class NetflixSettings extends PreferenceActivity implements
Preference.OnPreferenceChangeListener{
	private static final String TAG = "NetflixSettings";
	private static final String KEY_Netflix_Deactivation = "netflix_deactivation";
	private static final String KEY_Netflix_ESN = "netflix_esn";
    private ClearUserDataObserver mClearDataObserver;
    private ClearCacheObserver mClearCacheObserver;
    private static final int DIALOG_NETFLIX_RESET = 521;
	private PreferenceScreen mDeactivationPreference;
	private PreferenceScreen mESNPreference;
	public static final int REQUEST_MANAGE_SPACE = 2;
	
	@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        addPreferencesFromResource(R.xml.netflix_settings);
        mDeactivationPreference = (PreferenceScreen) findPreference(KEY_Netflix_Deactivation);
        updateEsnPreference();
    }
	@Override
	public boolean onPreferenceChange(Preference arg0, Object arg1) {
		return false;
	}
	protected Dialog onCreateDialog(int id){
		switch (id) {
        case DIALOG_NETFLIX_RESET: {
            final AlertDialog.Builder builder = new AlertDialog.Builder(this)
            //.setIconAttribute(android.R.attr.alertDialogIcon)
            .setTitle(R.string.netflix_deactivation)
            .setMessage(R.string.netflix_deactivation_message)
            .setPositiveButton(R.string.button_confirm, new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int whichButton) {
                    /* User clicked OK so do some stuff */
					Intent intent = new Intent(Intent.ACTION_DEFAULT);
                    intent.setClassName("com.google.tv.netflix",
                            "com.google.tv.netflix.SpaceManager");
					Log.i(TAG, "mAppEntry.info.packageName: " );
					Log.i(TAG, "mAppEntry.info.manageSpaceActivityName:");
                    startActivityForResult(intent, REQUEST_MANAGE_SPACE);
					
//                	clearNetflixUserData();
                }
            })
            .setNegativeButton(R.string.netflix_cancel, new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int whichButton) {

                    /* User clicked Cancel so do some stuff */
                }
            });
            return builder.create();
        }
        default:
            break;
    }
    return super.onCreateDialog(id);
	}
	@Override
	@Deprecated
	public boolean onPreferenceTreeClick(PreferenceScreen preferenceScreen,
			Preference preference) {
	if (preference == mDeactivationPreference) {
//		showDialog(DIALOG_NETFLIX_RESET);
		Intent intent = new Intent(Intent.ACTION_DEFAULT);
        intent.setClassName("com.google.tv.netflix",
         "com.google.tv.netflix.SpaceManager");
		Log.i(TAG, "mAppEntry.info.packageName: " );
		Log.i(TAG, "mAppEntry.info.manageSpaceActivityName:");
        startActivityForResult(intent, REQUEST_MANAGE_SPACE);
	}
		return super.onPreferenceTreeClick(preferenceScreen, preference);
	}
private  void clearNetflixUserData() {
        
        // Invoke uninstall or clear user data based on sysPackage
        String packageName = "com.google.tv.netflix";
        MyLog.i(TAG, "Clearing user data for package : " + packageName);
        if (mClearDataObserver == null) {
            mClearDataObserver = new ClearUserDataObserver();
			MyLog.i(TAG, "mClearDataObserver: " + mClearDataObserver);
        }
		if (mClearCacheObserver == null) {
            mClearCacheObserver = new ClearCacheObserver();
			MyLog.i(TAG, "mClearCacheObserver : " + mClearCacheObserver);
        }

        ActivityManager am = (ActivityManager)
                this.getSystemService(Context.ACTIVITY_SERVICE);
        boolean res = am.clearApplicationUserData(packageName, mClearDataObserver);
		this.getPackageManager().deleteApplicationCacheFiles(packageName, mClearCacheObserver);
		MyLog.i(TAG, "packageName : " + packageName);
        if (!res) {
            // Clearing data failed for some obscure reason. Just log error for now
        	MyLog.i(TAG, "Couldnt clear application user data for package:"+packageName);
            Toast.makeText(this, R.string.clear_failed_dlg_text, Toast.LENGTH_LONG)
                    .show();
        }
    }
class ClearUserDataObserver extends IPackageDataObserver.Stub {
    public void onRemoveCompleted(final String packageName, final boolean succeeded) {
			processClearMsg(succeeded);
	   }
 }

 private void processClearMsg(boolean succeeded) {
	    
	    String packageName = "com.google.tv.netflix";
	    
	    if(succeeded == true) {
	    	MyLog.i(TAG, "Cleared user data for package : "+packageName);
	        //mState.requestSize(packageName);
	    } 
	    checkForceStop();
	}
 private void checkForceStop() {
	 String packageName = "com.google.tv.netflix";
     Intent intent = new Intent(Intent.ACTION_QUERY_PACKAGE_RESTART,
     Uri.fromParts("package", packageName, null));
 }
 private void updateEsnPreference() {
     Preference esnPreference = findPreference(KEY_Netflix_ESN);
     String esn = "";

     String[] projection = {"esn"};
     ContentResolver resolver = getContentResolver();
	 try{
	 
     Cursor cursor = resolver.query(
             Uri.parse("content://com.google.tv.netflix/settings"), projection, null, null, null);
     MyLog.d(TAG, "cursor: " + cursor);

     if (null != cursor) {
         while (cursor.moveToNext()) {
             String key = cursor.getString(0);
             String value = cursor.getString(1);
             MyLog.d(TAG, "key: " + key + ", value: " + value);
             if (key.equals("esn")) {
                 // esn = cursor.getString(1);
                 esn = value;
                 break;
             }
         }

         cursor.close();
     }

     if (esn != null) {
         esnPreference.setSummary(esn);
     }
	 }catch(Exception e) {
			MyLog.d(TAG, "Exception: " );
    		e.printStackTrace();
    	}
 }
	class ClearCacheObserver extends IPackageDataObserver.Stub {
     public void onRemoveCompleted(final String packageName, final boolean succeeded) {
		MyLog.i(TAG, "Cleared Cache for package : "+succeeded);
      }
  }
	

}
